<?php

namespace builder\widget\ajax;

use builder\helper\H5;
use builder\helper\Url;
use builder\widget\BaseWidget;
use yii\base\InvalidArgumentException;
use yii\helpers\Json;

/**
 *块组件(modal)
 * ```php
 *  WidgetFacade::echo2Return(function () {
 *              BlockModal::begin([
 *                  'url' => 'user/create',
 *                  'closeCallback' => 'console.log("This is modal-close callback. ")',
 *                  'scope' => [
 *                      'param1' => 'default.Field1',
 *                  ],
 *              ]);
 *              echo '<button class="layui-btn layui-btn-sm layui-bg-light layui-border-theme"><i class="bi bi-box-arrow-in-down-right"></i> 动态按钮(modal)</button>';
 *              BlockModal::end();
 * });
 *
 * ```
 */
class BlockModal extends BaseWidget
{
    /**
     * @var array|string modal路由/地址
     */
    public $url;

    /**
     * @var string modal标题
     */
    public $title = ' ';

    /**
     * @var string modal宽
     */
    public $width = '620px';

    /**
     * @var string modal高
     */
    public $height = '750px';

    /**
     * @var int 是否允许底部关闭按钮
     */
    public $closeBtn = 0;

    /**
     * @var null|string modal关闭时回调，允许javascript表达式。
     */
    public $closeCallback = null;

    /**
     * @var string 模态框`iframe`的来源窗口
     * - self
     * - parent
     * - parent.parent.***
     */
    public $refererWindow = 'self';

    /**
     * angular字段
     * @var null|array
     */
    public $scope = null;

    /**
     * @var array 其他选项，如：attribute、class、style。
     */
    public $options = [];

    /**
     * @return void
     */
    public function initOptions()
    {
        if (empty($this->url)) {
            throw new InvalidArgumentException('The class ' . __CLASS__ . '::url is empty.');
        }

        $this->url = Url::to($this->url, '');
    }

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        $this->initOptions();

        echo H5::beginTag('ngx-block', array_merge($this->options, [
                'type' => 'modal',
                'url' => $this->url,
                'modal-title' => $this->title,
                'width' => $this->width,
                'height' => $this->height,
                'close-btn' => $this->closeBtn,
                'modal-close-callback' => $this->closeCallback,
                'referer-window' => $this->refererWindow,
                'scope' => $this->scope ? Json::htmlEncode($this->scope) : '',
            ])) . "\n";
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        echo H5::endTag('ngx-block') . "\n";
    }
}